<template>
  <section>
    <ody-list-search-area>
      <div slot="content">
        <el-form ref="form" label-width="100px" class="form">
<#list po.searchFields as field>
          <ody-search-item :label="$t('${field.title}')" :space="<#if field.date>2<#else>1</#if>">
          <#if field.tag??>
          <${field.tag} ref="${field.relName}" v-model="filters.${field.relName}"${field.tagAttrs!""} name="${field.relName}" />
          <#elseif field.dataSourceType?? && field.dataSourceType == "code">
            <el-select v-model="filters.${field.relName}" :placeholder="$t('全部')" name="${field.relName}">
              <el-option v-for="(value, key) in ${field.relName}Dict" :key="key" :label="value" :value="key"/>
            </el-select>
          <#elseif field.date>
            <ody-date-range-picker ref="${field.relName}Range" v-model="${field.relName}Range" :default="7" name="${field.relName}" />
          <#else>
            <el-input v-model="filters.${field.relName}" :placeholder="$t('请输入') + $t('${field.title}')" name="searchForm_filters_${field.relName}" />
          </#if>
          </ody-search-item>
        </#list>
        </el-form>
      </div>
      <div slot="btn">
        <el-button name="reset" size="small" @click="reset">{{ $t('common_reset') }}</el-button>
        <ody-button
          name="${po.name}_listPage_search"
          code="${po.name}_listPage"
          size="small"
          type="primary"
          @click="search"
        >{{ $t('common_select') }}</ody-button>
      </div>
    </ody-list-search-area>

    <ody-list-table-area>
      <div slot="btn">
        <ody-button
          name="${po.name}_exportData"
          code="${po.name}_add"
          size="small"
          @click="add"
        >{{ $t('newly_added') }}</ody-button>
        <#if showCheckbox?? && showCheckbox?boolean>
        <ody-button
          name="${po.name}_batchDelete"
          code="${po.name}_delete"
          size="small"
          @click="batchDelete"
        >{{ $t('common_batch_remove') }}</ody-button>
        </#if>
        <#if po.importable>
        <ody-batch-import-button
          :download-api="importModel.downloadApi"
          :import-api="importModel.importApi"
          :import-label="importModel.importlabel"
          :download-local="importModel.isDownloadLocal"
          :async="importModel.async"
          :pool="importModel.pool"
          :task-type="importModel.taskType"
          name="${po.name}_importData"
          code="${po.name}_importData"
          size="small"
        >{{ $t('batch_import') }}</ody-batch-import-button>
        </#if>
        <#if po.exportable>
        <ody-batch-export-button
          :get-export-data="exportModel.getExportData"
          :export-api="exportModel.exportApi"
          :async="exportModel.async"
          :pool="exportModel.pool"
          :task-type="exportModel.taskType"
          name="${po.name}_exportData"
          code="${po.name}_exportData"
          size="small"
        >{{ $t('batch_export') }}</ody-batch-export-button>
        </#if>
        <#if po.importable || po.exportable>
        <#if importAsync?boolean || exportAsync?boolean>
        <el-popover placement="bottom" with="160" trigger="hover">
          <div class="btn-popover">
          <#if po.importable && importAsync?boolean>
            <ody-import-task-button
              pool="${configPool}"
              task-type="${po.uncapName}Import"
              name="${po.name}_seeImportTask"
              code="${po.name}_importData"
              size="small"
            >{{ $t('seeImportTask') }}</ody-import-task-button>
          </#if>
          <#if po.exportable && exportAsync?boolean>
            <ody-export-task-button
              pool="${configPool}"
              task-type="${po.uncapName}Export"
              name="${po.name}_seeExportTask"
              code="${po.name}_exportData"
              size="small"
            >{{ $t('seeExportTask') }}</ody-export-task-button>
          </#if>
          </div>
          <el-button slot="reference" size="small">
            {{ $t('seeTask') }}
            <i class="el-icon-arrow-down" />
          </el-button>
        </el-popover>
        </#if>
        </#if>
      </div>
      <div slot="table">
        <ody-table
          v-loading="loading"
          <#if showCheckbox?? && showCheckbox?boolean>
          :checked.sync="checked"
          :multiple="true"
          </#if>
          :data="list"
          :columns="columns"
          :operates="operates"
          :can-filter="false"
          name="${po.uncapName}Table"
        />
      </div>
      <div slot="page">
        <el-pagination
          :current-page.sync="page.page"
          :page-sizes="[10, 20, 30, 50]"
          :page-size.sync="page.limit"
          :total.sync="total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="search"
          @current-change="search"
        />
      </div>
    </ody-list-table-area>
  </section>
</template>
<script>
export default {
  name: '${po.name}List',
  data() {
    return {
      <#if showCheckbox?? && showCheckbox?boolean>
      checked: [],
      </#if>
      <#if po.importable>
      importModel: {
        isDownloadLocal: true,
        importApi: ['${contextPath}', '${po.uncapName}', 'importData', {}],
        downloadApi: ['excelFile', '${po.uncapName}-template.xlsx'],
        importLabel: this.$t('导入${po.title}'),
        pool: '${configPool}',
        taskType: '${po.uncapName}Import',
        async: ${importAsync?string}
      },
      </#if>
      <#if po.exportable>
      exportModel: {
        exportApi: ['${contextPath}', '${po.uncapName}', 'exportData'],
        pool: '${configPool}',
        taskType: '${po.uncapName}Export',
        async: ${exportAsync?string},
        getExportData: () => {
          this.handleFilters()
          return this.filters
        }
      },
      </#if>
      loading: false,
      list: [],
      columns: [
      <#list po.tableFields as field>
        {
          label: this.$t('${field.title!field.relName}'),
          prop: '${field.relName}<#if field.dataSourceType?? && field.dataSourceType == "code">Str</#if>',
          show: true,
          align: <#if field.number>'right'<#else>'center'</#if>,
          minWidth: 120<#if field.date>,
          formatter: (row, column, cellValue) => {
            if (row.${field.relName}) {
              return this.$portal.parseTime(
                row.${field.relName},
                '{y}-{m}-{d} {h}:{i}:{s}'
              )
            }
          }</#if>
        }<#sep>,</#sep>
        </#list>
      ],
      operates: {
        fixed: 'right',
        width: 120,
        align: 'center',
        list: [
          {
            label: this.$t('查看'),
            code: '${po.name}_getById',
            method: (index, row) => {
              this.$router.push({
                name: '${po.name}Detail',
                query: {
                  id: row.id,
                  readonly: true
                }
              })
            }
          },
          {
            label: this.$t('编辑'),
            code: '${po.name}_update',
            method: (index, row) => {
              this.$router.push({
                name: '${po.name}Edit',
                query: {
                  id: row.id,
                  readonly: false
                }
              })
            }
          },
          {
            label: this.$t('删除'),
            code: '${po.name}_delete',
            method: (index, row) => {
              this.delete(row)
            }
          }
        ]
      },
      <#list po.searchFields as field>
        <#if field.date>
      ${field.relName}Range: [],
        <#elseif field.dataSourceType?? && field.dataSourceType == "code">
      ${field.relName}Dict: {},
        </#if>
      </#list>
      filters: {},
      page: {
        page: 1,
        limit: 10
      },
      total: 0
    }
  },
  mounted() {
    this.init()
  },
  activated() {
    this.init()
  },
  methods: {
    async init() {
      <#-- 判断是否含有字典 -->
      <#list po.searchFields as field>
      <#if field.dataSourceType?? && field.dataSourceType == "code">
      <#assign hasAnyDict = true>
      <#break>
      </#if>
      </#list>
      <#-- 是否含有字典 -->
      <#if hasAnyDict??>
      const categories = []
      <#list po.searchFields as field>
      <#if field.dataSourceType?? && field.dataSourceType == "code">
      categories.push('${field.dataSourceKey}')
      </#if>
      </#list>
      const res = await this.$${poolName}.$api.common.codeListMulti({ 'categories': categories })
      <#list po.searchFields as field>
      <#if field.dataSourceType?? && field.dataSourceType == "code">
      ${field.relName}Dict = res.data['${field.dataSourceKey}']
      </#if>
      </#list>
      </#if>
      this.search()
    },
    search() {
      this.loading = true

      this.handleFilters()
      const args = { filters: this.filters, ...this.page }
      this.$${poolName}.$api.${po.uncapName}.listPage(args).then(
        res => {
          this.loading = false
          this.list = res.data
          this.total = res.total
        },
        () => {
          this.loading = false
        }
      )
    },
    handleFilters() {
      <#list po.searchFields as field>
      <#if field.date>
      if (this.${field.relName}Range && this.${field.relName}Range.length > 1) {
        this.filters.start${field.capName} = this.${field.relName}Range[0]
        this.filters.end${field.capName} = this.${field.relName}Range[1]
      } else {
        delete this.filters.start${field.capName}
        delete this.filters.end${field.capName}
      }
      </#if>
      </#list>
    },
    reset() {
<#if showCheckbox?? && showCheckbox?boolean>
      this.checked = []
      </#if>
      this.filters = {}
      <#list po.searchFields as field>
      <#if field.date>
      this.${field.relName}Range = []
      this.$refs.${field.relName}Range.setDefault(7)
      </#if>
      </#list>
    },
    add() {
      this.$router.push({
        name: '${po.name}Add',
        query: {
          readonly: false
        }
      })
    },
<#if showCheckbox?? && showCheckbox?boolean>
    async batchDelete() {
      if (this.checked.length === 0) {
        return this.$message(this.$t('至少选择一条数据'))
      }
      const confirm = await this.$confirm(
        this.$t('是否删除选中的') + this.$t('${po.title}'),
        this.$t('common_prompt')
      )
      if (confirm) {
        if (this.checked && this.checked.length > 0) {
          const ids = this.checked.map(x => x['id'])
          const result = await this.$${poolName}.$api.${po.uncapName}.delete(ids)
          if (result && result.code === '0') {
            this.checked = []
            this.search()
            this.$message({
              type: 'success',
              message: this.$t('common_delete_success')
            })
          }
        }
      }
    },
    </#if>
    async delete(row) {
      const confirm = await this.$confirm(
        this.$t('是否删除当前') + this.$t('${po.title}'),
        this.$t('common_prompt')
      )
      if (confirm) {
        const ids = []
        ids.push(row.id)
        const result = await this.$${poolName}.$api.${po.uncapName}.delete(
          ids
        )
        if (result && result.code === '0') {
          this.search()
          this.$message({
            type: 'success',
            message: this.$t('common_delete_success')
          })
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
<#if po.importable || po.exportable>
<#if importAsync?boolean || exportAsync?boolean>
.popover-container {
  .popover-input {
    margin-bottom: 10px;
  }
}
.btn-popover {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  .el-button {
    margin-bottom: 4px;
  }
}
</#if>
</#if>
</style>
